//
//  YearStatisticView.swift
//  MakeMoney
//
//  Created by fan zhiqiang on 2024/12/19.
//

import SwiftUI

struct YearStatisticView: View {
    @Bindable var pathStore: PathStore
    let year: Int
    @State private var lotterys: [Lottery] = []
    @State private var statistic = LotteryStatistics()
    
    var body: some View {
        Form {
            Section {
                ForEach(1..<36) { index in
                    statisticsFrontRows(num: index, count: statistic.frontCountDictionary[index, default: 0])
                }
            } header: {
                Text("前区号码")
            } footer: {
                Text("应出现平均次数\(statistic.numAverage)")
            }
            
            Section {
                ForEach(1..<13) { index in
                    statisticsHindRows(num: index, count: statistic.hindCountDictionary[index, default: 0])
                }
            } header: {
                Text("后区号码")
            } footer: {
                Text("应出现平均次数\(statistic.noAverage)")
            }
            
            Section {
                ForEach(1..<4) { index in
                    statisticsBallRows(num: index, count: statistic.ballCountDictionary[index, default: 0])
                }
            } header: {
                Text("摇奖球")
            } footer: {
                Text("应出现平均次数\(statistic.ballAverage)")
            }
        }
        .navigationTitle("统计")
        .navigationDestination(for: StatisticAreaPath.self) { path in
            StatisticAreaView(pathStore: pathStore, year: year, param: path.param, statisticArea: path.area)
        }
        .onAppear {
            lotterys = getLotterysWith(range: getYearIdRange(with: year))
            statistic = getStatisticsWith(lotterys)
        }
        
    }
}

extension YearStatisticView {
    func statisticsFrontRows(num: Int, count: Int) -> some View {
        Button {
            pathStore.path.append(StatisticAreaPath(param: num, area: .front))
        } label: {
            HStack {
                Text("号码\(num)")
                Spacer()
                Text(count.formatted())
            }
        }
    }
    
    func statisticsHindRows(num: Int, count: Int) -> some View {
        Button {
            pathStore.path.append(StatisticAreaPath(param: num, area: .hind))
        } label: {
            HStack {
                Text("号码\(num)")
                Spacer()
                Text(count.formatted())
            }
        }
    }
    
    func statisticsBallRows(num: Int, count: Int) -> some View {
        Button {
            pathStore.path.append(StatisticAreaPath(param: num, area: .ball))
        } label: {
            HStack {
                Text("号码\(num)")
                Spacer()
                Text(count.formatted())
            }
        }
    }
}

#Preview {
    YearStatisticView(pathStore: .init(), year: 2024)
}

class YearStatisticPath: PathName { }
